package com.atgouwu.mall.order.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.atgouwu.mall.order.constant.AlipayTemplate;
import com.atgouwu.mall.order.service.OrderService;
import com.atgouwu.mall.order.vo.PayAsyncVo;
import com.atgouwu.mall.order.vo.PayVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.atgouwu.mall.order.entity.PaymentInfoEntity;
import com.atgouwu.mall.order.service.PaymentInfoService;
import com.atgouwu.mall.common.utils.PageUtils;
import com.atgouwu.mall.common.utils.R;

import javax.servlet.http.HttpServletRequest;

/**
 * 支付信息表
 *
 * @author heran
 * @email sunlightcs@gmail.com
 * @date 2024-02-22 15:15:23
 */
@Api(tags = "支付")
@RestController
@RequestMapping("order/paymentinfo")
public class PaymentInfoController {
    @Autowired
    private PaymentInfoService paymentInfoService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private AlipayTemplate alipayTemplate;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = paymentInfoService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        PaymentInfoEntity paymentInfo = paymentInfoService.getById(id);
        return R.ok().put("paymentInfo", paymentInfo);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody PaymentInfoEntity paymentInfo) {
        paymentInfoService.save(paymentInfo);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody PaymentInfoEntity paymentInfo) {
        paymentInfoService.updateById(paymentInfo);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        paymentInfoService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    //支付宝支付(返回html支付宝支付页)
    @ApiOperation(value = "支付宝支付")
    @GetMapping(value = "/api/aliPay")
    public R aliPay(@RequestParam("orderSn") String orderSn) throws AlipayApiException {
        PayVo payVo = orderService.getOrderPay(orderSn); //根据订单号获取订单
        String pay = alipayTemplate.pay(payVo); //支付
        return R.ok().put("data", pay);
    }

    //支付宝异步回调,只要收到支付宝异步通知,返回success支付宝就不再通知
    @PostMapping(value = "/payed/notify")
    public String handleAlipayed(PayAsyncVo asyncVo, HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = new HashMap<>(); //获取支付宝POST过来反馈信息
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8"); //解决乱码
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(params, alipayTemplate.getAlipay_public_key(), alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名
        if (signVerified) { //签名验证成功
            String result = orderService.handlePayResult(asyncVo); //修改订单状态
            return result;
        } else { //签名验证失败
            return "error";
        }
    }

    //微信异步回调
//    @PostMapping(value = "/pay/notify")
//    public String asyncNotify(@RequestBody String notifyData) {
//        //异步通知结果
//        return orderService.asyncNotify(notifyData);
//    }

}
